package udpserver

import (
	"fmt"
	"net"
	"sync"
)

const (
	receiveMTU           = 8192 // 读取的缓冲区大小
	defaultListenBacklog = 128  // same as Linux default
)

type UdpServer struct {
	option *UdpOption
}

// NewUdpServer 使用输入的UDP配置，创建一个UDP服务器
func NewUdpServer(option *UdpOption) *UdpServer {
	return &UdpServer{
		option: option,
	}
}

// NewConnection 创建一个新的连接对象
func (u *UdpServer) NewConnection() *Connection {
	return &Connection{}
}

// getAddr 获取一个UDPAddr地址
func (u UdpServer) getAddr() (*net.UDPAddr, error) {
	return net.ResolveUDPAddr("udp", u.option.Address())
}

// Listen 开启服务器监听
func (u *UdpServer) Listen() (net.Listener, error) {
	if u.option.Backlog == 0 {
		u.option.Backlog = defaultListenBacklog
	}

	addr, err := u.getAddr()
	if err != nil {
		return nil, err
	}

	conn, err := net.ListenUDP("udp", addr)
	if err != nil {
		return nil, err
	}
	// 创建一个UDP监听对象
	l := &listener{
		udpConn:      conn,
		connections:  make(map[string]*Connection),
		acceptCh:     make(chan *net.Conn, u.option.Backlog),
		acceptFilter: u.option.AcceptFilter,
		doneCh:       make(chan struct{}),
		readBufferPool: &sync.Pool{
			New: func() interface{} {
				buf := make([]byte, receiveMTU)
				return &buf
			},
		},
	}

	l.accepting.Store(true)
	defer func() {
		l.Close()
		fmt.Println("Server Stop")
	}()

	l.Run()
	return nil, err
}
